package com.ttc.group2.videochat.activity;


import java.util.List;

import org.jivesoftware.smack.XMPPException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.quickblox.core.QBCallback;
import com.quickblox.core.QBEntityCallbackImpl;
import com.quickblox.core.QBSettings;
import com.quickblox.core.result.Result;
import com.quickblox.auth.QBAuth;
import com.quickblox.auth.model.QBSession;
import com.quickblox.auth.result.QBSessionResult;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.listeners.*;
import com.quickblox.users.QBUsers;
import com.quickblox.users.model.QBUser;
import com.quickblox.videochat.core.QBVideoChatController;
import com.ttc.group2.videochat.user.DataHolder;
import com.ttc.group2.videochat.user.DialogUtils;
import com.ttc.group2.videochat.utils.Utils;
import com.ttc.group2.videochat.R;


public class LoginActivity extends BaseActivity {
	
	private ProgressDialog progressDialog;
	
	private Context context;
	
	private EditText loginEditText;
	private EditText passwordEditText;

	private Button btnLogin;
	private Button btnSignUp;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sign_in_activity);
		
		context = this;
		
		initUI();
		
//		getView();

		/** set view */
		

		/** Set QuickBlox credentials */
		QBSettings.getInstance().fastConfigInit(Utils.APP_ID, Utils.AUTH_KEY, Utils.AUTH_SECRET);
		

        // Create QuickBlox session
        //
        QBAuth.createSession(new QBEntityCallbackImpl<QBSession>() {
            @Override
            public void onSuccess(QBSession qbSession, Bundle bundle) {
            	setView();
//            	showHomeActivity();
            }

            @Override
            public void onError(List<String> errors) {
                // print errors that came from server
                DialogUtils.showLong(context, errors.get(0));
//                progressBar.setVisibility(View.INVISIBLE);
            }
        });
//		checkLoggedIn();
		
	}
	
	
	private void initUI() {
//		mActionbar.setDisplayHomeAsUpEnabled(true);
		loginEditText = (EditText) findViewById(R.id.edtGroupName);
		passwordEditText = (EditText) findViewById(R.id.people_item_message);
		
		btnLogin = (Button) findViewById(R.id.call_btn_Mute);
		btnSignUp = (Button) findViewById(R.id.main_btnSignUp);

		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage(getString(R.string.please_wait));
		progressDialog.setCancelable(false);
		
	}
	
	void checkLoggedIn() {

		if (QBChatService.getInstance().isLoggedIn()) {
			showHomeActivity();
		}
	}
	
	void setView() {
		OnEditorActionListener onEditorActionListener = new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_DONE) {
					return setLogIn();
				}
				return false;
			}
		};
		OnClickListener onClickListener = new OnClickListener() {

			@Override
			public void onClick(View view) {
				onBtnClick(view);

			}
		};

		loginEditText.setOnEditorActionListener(onEditorActionListener);
		passwordEditText.setOnEditorActionListener(onEditorActionListener);

		btnLogin.setOnClickListener(onClickListener);
		btnSignUp.setOnClickListener(onClickListener);
	}
	
	boolean checkInputs() {
		boolean flag = false;
		if (!passwordEditText.getText().toString().equals("")) {
			loginEditText.requestFocus();
			flag = true;
		}
		if (!loginEditText.getText().toString().equals("")) {
			passwordEditText.requestFocus();
		} else {
			return false;
		}

		if (flag) {
			return true;
		}
		return false;
	}

	/**
	 * log user in
	 * 
	 * @return return true if login valid and false if not
	 */
	boolean setLogIn() {
		if (checkInputs()) {
//			progressDialog.show();
//			createSession(editUserName.getText().toString(), editPassword
//					.getText().toString());
				
		       progressDialog.show();

               // Sign in application with user
               //
               QBUser qbUser = new QBUser(loginEditText.getText().toString(), passwordEditText.getText().toString());
               QBUsers.signIn(qbUser, new QBEntityCallbackImpl<QBUser>() {
                   @Override
                   public void onSuccess(QBUser qbUser, Bundle bundle) {
                       progressDialog.hide();

                       setResult(RESULT_OK);

                       DataHolder.getDataHolder().setSignInQbUser(qbUser);
                       // password does not come, so if you want use it somewhere else, try something like this:
                       DataHolder.getDataHolder().setSignInUserPassword(passwordEditText.getText().toString());
//                       DialogUtils.showLong(context, getResources().getString(R.string.user_successfully_sign_in));

//                       finish();
                       showHomeActivity();
                   }

                   @Override
                   public void onError(List<String> errors) {
                       progressDialog.hide();
                       DialogUtils.showLong(context, errors.get(0));
                   }
               });
			
			return true;
		}
		return false;
	}

	void onBtnClick(View view) {
		int i=view.getId();
		if(i==R.id.call_btn_Mute){
			setLogIn();
		}
		else if(i==R.id.main_btnSignUp){
			showSignUpActivity();
		}
	}

	@Override
	public void onResume() {
		progressDialog.dismiss();
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}
	
	private void showSignUpActivity() {
		Intent i = new Intent(this, SignUpActivity.class);
		startActivity(i);
	}

	private void showHomeActivity() {
		Intent intent = new Intent(this, SplashActivity.class);
//		intent.putExtra("userId", DataHolder.getInstance().getCurrentQbUser()
//				.getId());
		startActivity(intent);
		finish();
	}
}
